package com.qk.filter;

import com.qk.utils.CurrentUserHoler;
import com.qk.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebFilter(urlPatterns = "/*")
public class tokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServiceRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServiceResponse = (HttpServletResponse) servletResponse;

        String requestURI = httpServiceRequest.getRequestURI();
        if (requestURI.contains("login")){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

        String token = httpServiceRequest.getHeader("token");
        if (token == null || token.isEmpty()){
            httpServiceResponse.setStatus(401);
            return;
        }

        try {
            Claims claims = JwtUtils.parseToken(token);
            CurrentUserHoler.setCurrentUser(claims.get("id",Integer.class));
        } catch (Exception e) {
            httpServiceResponse.setStatus(401);
            return;
        }

        filterChain.doFilter(servletRequest,servletResponse);
        CurrentUserHoler.removeCurrentUser();
    }
}
